package com.xuelang.pipeline.entry.common.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import io.kubernetes.client.custom.Quantity;
import io.kubernetes.client.custom.Quantity.Format;
import io.kubernetes.client.custom.QuantityFormatter;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * <p>V1PodList中Quantity的反序列化类</p>
 *
 * @author : yixin.lys
 * @date : 2024-07-16 15:09
 **/
public class QuantityDeserializer extends JsonDeserializer<Quantity> {
    private final QuantityFormatter quantityFormatter = new QuantityFormatter();

    @Override
    public Quantity deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode node = p.getCodec().readTree(p);
        if (node.isObject()) {
            JsonNode numberNode = node.get("number");
            JsonNode formatNode = node.get("format");
            if (numberNode != null && formatNode != null) {
                BigDecimal number = numberNode.decimalValue();
                Format format = Format.valueOf(formatNode.asText());
                return new Quantity(number, format);
            }
        } else if (node.isTextual()) {
            return quantityFormatter.parse(node.asText());
        }
        throw new IOException("Invalid Quantity format: " + node.toString());
    }
}
